package com.bawei.lib_storage.room.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import com.bawei.lib_storage.room.entity.HistoryEntity

@Dao
interface HistoryDao {
    /** 查询最新5条历史记录（全部用户） */
    @Query("select * from b_history order by id desc limit 5")
    fun getAll():List<HistoryEntity>

    /** 查询指定用户最新5条历史记录 */
    @Query("select * from b_history where userId = :userId order by id desc limit 5")
    fun getAllByUserId(userId: String):List<HistoryEntity>

    /** 分页查询指定用户的历史记录 */
    @Query("select * from b_history where userId = :userId order by id desc limit (:page * :pagesize) ,:pagesize")
    fun getAllByUserIdAndPage(userId: String, page: Int, pagesize:Int):List<HistoryEntity>

    /** 分页查询全部历史记录 */
    @Query("select * from b_history order by id desc limit (:page * :pagesize) ,:pagesize")
    fun getAllByPage(page: Int,pagesize:Int):List<HistoryEntity>

    /** 根据关键词模糊查询全部历史记录 */
    @Query("select * from b_history where content like  '%'+:keywords+'%'  order by id desc ")
    fun getAllByKeyWords(keywords:String):List<HistoryEntity>

    /** 根据关键词模糊查询指定用户的历史记录 */
    @Query("select * from b_history where userId = :userId and content like  '%'+:keywords+'%'  order by id desc ")
    fun getAllByUserIdAndKeyWords(userId: String, keywords:String):List<HistoryEntity>

    /** 插入一条或多条历史记录 */
    @Insert
    fun insertAll(vararg  entity: HistoryEntity)

    /** 删除指定历史记录 */
    @Delete
    fun delete(entity: HistoryEntity)

    /** 删除全部历史记录 */
    @Query("delete from b_history")
    fun deleteAll()

    /** 删除指定用户的全部历史记录 */
    @Query("delete from b_history where userId = :userId")
    fun deleteAllByUserId(userId: String)

    /** 根据id更新进度百分比 */
    @Query("UPDATE b_history SET progress = :progress WHERE id = :id")
    fun updateProgressById(id: Long, progress: Int)

    /** 根据id更新观看到的毫秒数 */
    @Query("UPDATE b_history SET lastPosition = :lastPosition WHERE id = :id")
    fun updateLastPositionById(id: Long, lastPosition: Long)

    /** 根据id更新videoId */
    @Query("UPDATE b_history SET videoId = :videoId WHERE id = :id")
    fun updateVideoIdById(id: Long, videoId: String)

    /** 根据videoId查找历史记录 */
    @Query("SELECT * FROM b_history WHERE videoId = :videoId LIMIT 1")
    fun getByVideoId(videoId: String): HistoryEntity?
}